package com.springboot.cloud.sysadmin.organization.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.ContentTypeDelegatingMessageConverter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class BusConfig {

    /*
      修改的内容：
      定义了两个队列，一个主题交换。通过两个不同的routing_key讲路由和主题绑定一起
     */

    public static final String QUEUE_NAME_O = "event-organization";
    public static final String QUEUE_NAME_R = "event-organization-role";
    public static final String EXCHANGE_NAME = "spring-boot-exchange";
    public static final String ROUTING_KEY_O = "organization-resource";
    public static final String ROUTING_KEY_R = "organization-role-reset";

    @Bean
    Queue queueO() {
        log.info("queue name:{}", QUEUE_NAME_O);
        return new Queue(QUEUE_NAME_O, false);
    }

    @Bean
    Queue queueR() {
        log.info("queue name:{}", QUEUE_NAME_R);
        return new Queue(QUEUE_NAME_R, false);
    }

    @Bean
    TopicExchange exchange() {
        log.info("exchange:{}", EXCHANGE_NAME);
        return new TopicExchange(EXCHANGE_NAME);
    }


    @Bean
    Binding bindingO( TopicExchange exchange) {
        Queue queue = queueO();
        log.info("binding {} to {} with {}", queue, exchange, ROUTING_KEY_O);
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY_O);
    }
    @Bean
    Binding bindingR( TopicExchange exchange) {
        Queue queue = queueR();
        log.info("binding {} to {} with {}", queue, exchange, ROUTING_KEY_R);
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY_R);
    }

    @Bean
    public MessageConverter messageConverter() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        return new ContentTypeDelegatingMessageConverter(new Jackson2JsonMessageConverter(objectMapper));
    }

}
